package com.yeskery.nut.util.banner;

import com.yeskery.nut.core.BasicNutConfigure;
import com.yeskery.nut.core.ByteArrayEnvironmentResource;
import com.yeskery.nut.core.ClassPathEnvironmentResource;
import com.yeskery.nut.core.EnvironmentResource;
import com.yeskery.nut.util.IOUtils;

import java.nio.charset.StandardCharsets;

/**
 * Nut启动Banner对象
 * @author sprout
 * @version 1.0
 * 2022-09-12 16:33
 */
public class NutBanner {

    /** Nut Banner实例对象 */
    private final static NutBanner NUT_BANNER = new NutBanner();

    /** banner内容信息 */
    private static final String BANNER_CONTEXT = " _   _       _                             _ _           _   _\n" +
            "| \\ | |     | |          /\\               | (_)         | | (_)\n" +
            "|  \\| |_   _| |_ ______ /  \\   _ __  _ __ | |_  ___ __ _| |_ _  ___  _ __\n" +
            "| . ` | | | | __|______/ /\\ \\ | '_ \\| '_ \\| | |/ __/ _` | __| |/ _ \\| '_ \\\n" +
            "| |\\  | |_| | |_      / ____ \\| |_) | |_) | | | (_| (_| | |_| | (_) | | | |\n" +
            "|_| \\_|\\__,_|\\__|    /_/    \\_\\ .__/| .__/|_|_|\\___\\__,_|\\__|_|\\___/|_| |_|\n" +
            " :: Nut Version ::            | |   | |                  (${nut.version})\n" +
            " :: Build Time  ::            |_|   |_|                (${nut.buildTime})";

    /** 默认的banner文件名称 */
    private static final String DEFAULT_BANNER_FILE_NAME = "banner.txt";

    /** 绝对类资源前缀 */
    private static final String ABS_CLASS_RESOURCE_PREFIX = "/";

    /** Nut Banner环境资源对象 */
    private final EnvironmentResource bannerEnvironmentResource;

    /** banner环境对象 */
    private final BannerEnvironment bannerEnvironment;

    /**
     * 构建Nut启动Banner对象
     */
    private NutBanner() {
        bannerEnvironment = new BannerEnvironment();
        if (this.getClass().getResource(ABS_CLASS_RESOURCE_PREFIX + DEFAULT_BANNER_FILE_NAME) == null) {
            bannerEnvironmentResource = new ByteArrayEnvironmentResource(bannerEnvironment,
                    "banner", BANNER_CONTEXT.getBytes(StandardCharsets.UTF_8));
        } else {
            bannerEnvironmentResource = new ClassPathEnvironmentResource(bannerEnvironment, DEFAULT_BANNER_FILE_NAME);
        }
    }

    /**
     * 输出banner信息
     * @param basicNutConfigure nut配置信息
     */
    public void printBanner(BasicNutConfigure basicNutConfigure) {
        if (basicNutConfigure.isPrintBanner()) {
            System.out.println(IOUtils.readAsString(bannerEnvironmentResource.getInputStream()));
        }
    }

    /**
     * 添加banner属性
     * @param key 属性名称
     * @param value 属性值
     */
    public void addProperty(String key, String value) {
        bannerEnvironment.getEnvProperties().setProperty(key, value);
    }

    /**
     * 获取Banner实例
     * @return Banner实例
     */
    public static NutBanner getInstance() {
        return NUT_BANNER;
    }
}
